package com.jwsoft.manager.core.dao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bifang.engine.assistant.core.enums.BoolEnum;
import com.bifang.engine.assistant.core.exception.AppException;
import com.bifang.module.base.common.util.CommonSecureUtil;
import com.jwsoft.manager.common.enums.EduStatusTypeEnum;
import com.jwsoft.manager.common.vo.eduDataTaskDetail.DataTaskDetailOptionVO;
import com.jwsoft.manager.core.dao.mapper.EduhStudentEnrollFamilyMapper;
import com.jwsoft.manager.core.dao.mapper.EdutStudentEnrollFamilyMapper;
import com.jwsoft.manager.core.dao.model.*;
import com.jwsoft.manager.core.dao.mapper.EduStudentEnrollFamilyMapper;
import com.jwsoft.manager.core.dao.service.EduDataTaskDetailService;
import com.jwsoft.manager.core.dao.service.EduStudentEnrollFamilyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jwsoft.manager.core.dao.service.TableService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 服务实现类
 *
 * @author wangtao
 * @since 2022-11-25
 */
@Service
@Slf4j
public class EduStudentEnrollFamilyServiceImpl extends ServiceImpl<EduStudentEnrollFamilyMapper, EduStudentEnrollFamily> implements EduStudentEnrollFamilyService, TableService {

    @Autowired
    private EduDataTaskDetailService detailService;

    @Autowired
    private TransactionTemplate transactionTemplate;

    @Autowired
    private EduhStudentEnrollFamilyMapper hFamilyMapper;

    @Autowired
    private EdutStudentEnrollFamilyMapper tFamilyMapper;

    private static final String STUDENT_ENROLL_PRE_TABLE = "edu_student_enroll_pre";

    //每次处理的数量为1w条数据
    private static final Integer PAGE_SIZE = 1000;
    @Override
    public void delByPreId(String studentEnrollPreId) {
        this.baseMapper.delByPreId(studentEnrollPreId);
    }

    @Override
    public void removeByPreId(String studentEnrollPreId) {
        this.baseMapper.removeByPreId(studentEnrollPreId);
    }

    @Override
    public Integer dataMigration(DataTaskDetailOptionVO optionVO) {
        EduDataTaskDetail taskDetail = detailService.getById(optionVO.getTaskDetailId());
        log.info("调用了EduStudentEnrollFamilyServiceImpl服务的dataMigration()来进行处理迁移数据");
        //判断主表数据是否执行过数据迁移
        Boolean queryHistory = detailService.verifyQueryHistory(optionVO.getYear(), STUDENT_ENROLL_PRE_TABLE);
        if (!queryHistory){
            throw new AppException("edu_student_enroll_pre未执行数据迁移，无法迁移"+taskDetail.getHandleTable()+"的数据");
        }
        //根据主表已迁移的数据，查出需要迁移的数据
        // 获取待迁移数据总数
        Integer count = this.baseMapper.countMigrationData(optionVO.getYear());
        log.info("edu_student_enroll_family迁移" + count + "条数据");

        // List<EduStudentEnrollFamily> studentEnrollFamilyList = new ArrayList<>();
        // Integer count = 0;
        int totalPages = (count % PAGE_SIZE == 0) ? (count / PAGE_SIZE) : (count / PAGE_SIZE + 1);
        // 计算循环次数 = 总页数
        for (int i = 0; i < totalPages; i++) {
            List<EduStudentEnrollFamily> studentEnrollFamilyList
                    = this.baseMapper.selectMigrationByPre(optionVO.getYear(),PAGE_SIZE);
            if (studentEnrollFamilyList.size() > 0 ){
                List<EduhStudentEnrollFamily> hEnrollFamilyList = studentEnrollFamilyList.stream().map(item -> {
                    EduhStudentEnrollFamily hEnrollFamily = new EduhStudentEnrollFamily();
                    BeanUtils.copyProperties(item, hEnrollFamily);
                    hEnrollFamily.setTaskDetailId(taskDetail.getTaskDetailId());
                    hEnrollFamily.setEncryptFlag(BoolEnum.FALSE.getType());
                    hEnrollFamily.setEncryptStatus(EduStatusTypeEnum.dcl.getType());
                    hEnrollFamily.setCleanFlag(BoolEnum.FALSE.getType());
                    return hEnrollFamily;
                }).collect(Collectors.toList());
                try {
                    this.performDataMigration(hEnrollFamilyList, studentEnrollFamilyList.size() , optionVO);
                } catch (Exception e) {
                    log.error("edu_student_enroll_family迁移数据发生异常");
                    throw new RuntimeException("EduStudentEnrollFamilyServiceImpl:" + e);
                }
            }
        }
        return count;
    }

    private void performDataMigration(List<EduhStudentEnrollFamily> hEnrollFamilyList, Integer count, DataTaskDetailOptionVO optionVO) {
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                try {
                    //1.数据迁移到历史表
                    int saveHCount = hFamilyMapper.saveBatch(hEnrollFamilyList);
                    if (saveHCount != count) {
                        throw new RuntimeException("数据迁移到历史表失败");
                    }
                    //2.数据销毁
                    EduDataTaskDetail taskDetail = detailService.getById(optionVO.getTaskDetailId());
                    if (ObjectUtils.isEmpty(taskDetail)) {
                        throw new AppException("任务数据不存在，请检查数据是否有误");
                    }
                    Integer deleteCount = baseMapper.deleteByTaskHistory(taskDetail.getTaskDetailId());
                    if (!count.equals(deleteCount)) {
                        throw new RuntimeException("数据删除失败");
                    }
                    log.info("edu_student_enroll_family数据销毁成功！销毁数量：" + count);
                } catch (Exception e) {
                    status.setRollbackOnly();
                    throw e;
                }
            }
        });
        }

    @Override
    public void dataEncryption(DataTaskDetailOptionVO optionVO) {
        EduDataTaskDetail taskDetail = detailService.getById(optionVO.getTaskDetailId());
        log.info("调用了EduStudentEnrollFamilyServiceImpl服务的dataEncryption()来进行处理数据加密");
        Integer count = 0 ;
        if (taskDetail.getEncryptCount() == 0) {
            count = this.baseMapper.selectEncryptionCountByYear( optionVO.getTaskDetailId());
            taskDetail.setEncryptCount(count);
        }
        Boolean errorFlag = false;
        Integer errorCount = 0;
        int totalPages = (count % PAGE_SIZE == 0) ? (count / PAGE_SIZE) : (count / PAGE_SIZE + 1);
        // 计算循环次数 = 总页数
        for (int i = 0; i < totalPages; i++) {
            List<EduhStudentEnrollFamily> hStudentEnrollFamilies =
                    this.baseMapper.selectEncryptionByYear(optionVO.getTaskDetailId(), PAGE_SIZE);
            for (EduhStudentEnrollFamily enrollFamily : hStudentEnrollFamilies) {
                try {
                    this.encrypt(enrollFamily);
                    enrollFamily.setEncryptTime(new Date());
                    enrollFamily.setEncryptStatus(EduStatusTypeEnum.success.getType());
                    enrollFamily.setEncryptRemarks("加密成功");
                    enrollFamily.setEncryptFlag(BoolEnum.TRUE.getType());
                    hFamilyMapper.updateById(enrollFamily);
                }catch (Exception e){
                    this.decrypt(enrollFamily);
                    enrollFamily.setEncryptTime(new Date());
                    enrollFamily.setEncryptStatus(EduStatusTypeEnum.error.getType());
                    enrollFamily.setEncryptFlag(BoolEnum.FALSE.getType());
                    enrollFamily.setEncryptRemarks("加密失败"+e.getMessage());
                    hFamilyMapper.updateById(enrollFamily);
                    errorFlag = true;
                    errorCount++;
                    throw new AppException(e);
                }
            }
        }
        if (!errorFlag) {
            //无异常，返回任务状态
            taskDetail.setEncryptStatus(EduStatusTypeEnum.success.getType());
            taskDetail.setEncryptRemarks("加密成功");
            taskDetail.setEncryptTime(new Date());
        } else {
            taskDetail.setEncryptStatus(EduStatusTypeEnum.error.getType());
            taskDetail.setEncryptTime(new Date());
            taskDetail.setEncryptRemarks(taskDetail.getHandleTable()
                    +"加密失败,加密出错的数据：" + errorCount);
        }
        detailService.updateById(taskDetail);
    }

    private void decrypt(EduhStudentEnrollFamily enrollFamily) {
        if (StringUtils.isNotBlank(enrollFamily.getFullName())){
            enrollFamily.setFullName(CommonSecureUtil.sm4Decrypt(enrollFamily.getFullName()));
        }
        if (StringUtils.isNotBlank(enrollFamily.getIdcard())){
            enrollFamily.setIdcard(CommonSecureUtil.sm4Decrypt(enrollFamily.getIdcard()));
        }
    }

    private void encrypt(EduhStudentEnrollFamily enrollFamily) {
        if (StringUtils.isNotBlank(enrollFamily.getFullName())){
            enrollFamily.setFullName(CommonSecureUtil.sm4Encrypt(enrollFamily.getFullName()));
        }
        if (StringUtils.isNotBlank(enrollFamily.getIdcard())){
            enrollFamily.setIdcard(CommonSecureUtil.sm4Encrypt(enrollFamily.getIdcard()));
        }
    }

    @Override
    public Integer dataDestruction(DataTaskDetailOptionVO optionVO) {
        return null;
    }

    @Override
    public void tempDataDestruction() {

    }

    @Override
    public void dataDecrypt(DataTaskDetailOptionVO optionVO) {
        Integer count = Math.toIntExact(hFamilyMapper.selectCount
                (new QueryWrapper<EduhStudentEnrollFamily>().lambda().eq(EduhStudentEnrollFamily::getTaskDetailId, optionVO.getTaskDetailId())));
        // 计算总页数
        int totalPages = (count % PAGE_SIZE == 0) ? (count / PAGE_SIZE) : (count / PAGE_SIZE + 1);
        int currentPage = 0;
        // 计算循环次数 = 总页数
        for (int i = 0; i < totalPages; i++) {
            List<EduhStudentEnrollFamily> hEnrollFamilies =
                    hFamilyMapper.selectByTaskDetailId(optionVO.getTaskDetailId(),currentPage,PAGE_SIZE);
            List<EdutStudentEnrollFamily> tEnrollFamilies = hEnrollFamilies.stream().map(item -> {
                if (BoolEnum.TRUE.getType().equalsIgnoreCase(item.getEncryptFlag())) {
                    //需要进行解密
                    this.decrypt(item);
                }
                EdutStudentEnrollFamily tEnrollFamily = new EdutStudentEnrollFamily();
                BeanUtils.copyProperties(item, tEnrollFamily);
                return tEnrollFamily;
            }).collect(Collectors.toList());
            tFamilyMapper.saveBatch(tEnrollFamilies);
            currentPage ++;
        }
    }
}
